import { animate, state, style, transition, trigger } from '@angular/animations';
import { ChangeDetectorRef, Component, ElementRef, OnInit, Renderer2, ViewChild, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

import { CaseReviewService } from '../../../../../@core/service/case-review/case-review.service';
import { BizfileService } from '../../../../../@core/service/case-review/doc-service/api/bizfile.service';
import { DocsService } from '../../../../../@core/service/docs-service/docs-service.service';
import { StakeHolderService } from '../../../../../@core/service/handle-service/api/stakeHolder.service';
import { ngCopy } from 'angular-6-clipboard';
import { CaseDocService } from '../../../../../@core/service/handle-service/api/caseDoc.service';
import { TaskService } from '../../../../../@core/service/task-serivce/api/task.service'
import { VgAPI, VgPlayer } from 'videogular2/compiled/core';
import { DomSanitizer } from '@angular/platform-browser';  
// 证据service
import { EvidenceService } from '../../../../../@core/service/evidence/api/evidence.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { flyIn } from "./animate";
import { MessagerService } from "ng-easyui/components/messager/messager.service"

// 自定义接口
import { TaskSearchParmeter } from './interface'
import { forEach } from '@angular/router/src/utils/collection';
@Component({
  selector: 'app-detail-steps',
  templateUrl: './detail_steps.component.html',
  styleUrls: ['./detail_steps.component.scss'],
  animations: [
    trigger('openClose', [
      state('open', style({
        height: '150px',
        opacity: 1,
      })),
      state('closed', style({
        height: '25px',
        opacity: 0.5,
      })),
      transition('open => closed', [
        animate('0.3s'),
      ]),
      transition('closed => open', [
        animate('0.3s'),
      ]),
    ]),
    flyIn
  ],
})
export class DetailStepsComponent implements OnInit {
  bizfile: any = []                   // 文书列表
  bizfileListOther: any = [];         // 其他文书列表
  evidenceList: any = [];             // 证据列表
  isExpand: boolean = true;
  rightElement: any;


  constructor(
    public router: Router,
    private message: NzMessageService,       // 弹窗
    private alert:MessagerService,
    public evidence: EvidenceService,        // 证据service
    private bizfileService: BizfileService,  // 文书serivce
    private cdRef: ChangeDetectorRef,
    private active: ActivatedRoute,
    private stakeHolderService: StakeHolderService,
    public caseReview: CaseReviewService,
    private docsService: DocsService,
    private render2: Renderer2,
    private el: ElementRef,
    private taskService: TaskService,
    public caseDocService: CaseDocService,
    private sanitizer: DomSanitizer
  ) { }

  url:any = './audio@2x.png';

  public approveFlow: any[] = [];           // 文书流转

  // 流程节点数据
  public processNodes = [
    { name: '线索', processName: '线索', value: 'clue', documentData: [], evidenceData: [] },
    { name: '立案', processName: '立案', value: 'filing', documentData: [], evidenceData: [] },
    { name: '调查取证', processName: '调查<br>取证', value: 'survey', documentData: [], evidenceData: [] },
    { name: '处罚决定', processName: '处罚<br>决定', value: 'decide', documentData: [], evidenceData: [] },
    { name: '执行与结案', processName: '执行<br>与结案', value: 'case', documentData: [], evidenceData: [] },
    { name: '强制执行', processName: '强制<br>执行', value: 'measure', documentData: [], evidenceData: [] },
  ];


  // 全选控制
  public allChecked: boolean = false;

  // 文件状态数据
  public fileStatus = {
    loading: '审批中',
    success: '审批完成',
    none: '',
  };



  public sendMsg: object = {};
  public isOpen = false;
  public registerContent = '';             // 案件详情
  public insertDate = '';                  // 线索登记时间
  public fileType = '';                    // 文件类型
  public loading = false;                  // 数据加载动画
  public type = '';                        // 路由参数 区分从案件处理还是案件审批中进入
  public oprea: string;                    // 路由参数 区分是查看还是审批或办理的操作
  public registUerName = '';               // 登记人员名称
  public caseUserName: string[];           // 办案人员名称
  public paramId: string;                  // 案件id
  public uploadTime: string;               // task当前任务时间
  public handleMatters: Array<TaskSearchParmeter>  // task列表

  public taskFiles: any = []                // 终端tasks列表 
  public segment: any = null;                // 环节

  cmsCaseInfo: any = {
    partyName: '',
    addressDetail: '',
    partyPhone: '',
    partyOtherPhone: ''
  };          // 案件信息
  api: VgAPI;
  // 证据查看
  public publictypeFlag = '';        // 
  public renameIsShow = false;       // 改名标示
  public renameFile:any;             // 改名元素
  public renameSpan:boolean;         // renameSpan
  public fileId: any = null;         // 证据的文件ID
  public isVisible = false;          // 证据查看

  ngOnInit() {
    this.paramId = this.active.snapshot.params['id'];
    this.oprea = this.active.snapshot.params['opera'];
    this.type = this.active.snapshot.params['type'];
    this.getFileList(this.paramId);
    this.getEvidenceList(this.paramId);
    this.sendMsg['id'] = this.paramId;
    this.sendMsg['type'] = this.type;
    this.rightElement = this.findElement(this.el.nativeElement, 'steps-right-normal')[0];
    this.getTasks();
    // this.calcTerminalHeight();
  }

  //  动态计算右侧高度
  calcTerminalHeight() {
    this.rightElement.style.height = (this.el.nativeElement.scrollHeight + 55) + 'px';
  }
  // checkbox 修改状态
  changeLog($event){

  }

  // 挂接任务
  updateTaskFileStatus(): void {
    if (this.taskFiles <= 0) {
      this.message.create('error', `无可上传数据！`); return;
    }
    if (!this.segment) {
      this.message.create('error', `请选择案件环节！`); return;
    }

    let FileStatus = this.findFileIds().map(item => {
      if(item){
        return { fileId: item, stage: this.segment }
      }
    });
    this.taskService.updateTaskFileStatus(FileStatus).subscribe((data: any) => {
      this.getTasks();
      this.getFileList(this.paramId);
      this.getEvidenceList(this.paramId);
      this.message.create('success', `上传成功！`);
    });
  }

  findFileIds(): any {
    let filesId: any[] = [];
    this.taskFiles.forEach(item => {
      filesId.push(
        ...this.findFileId(item.files),
        ...this.findRemarkList(item.remarkList),
      )
    })
    return this.compact(filesId);
  }
  // 筛选问题列表
  findRemarkList(remark):string[]{
     let remarkIds:string[] = []
     remark.forEach((item:any)=>{
       if(item.attachmentList){
        remarkIds.push(...this.findFileId(item.attachmentList) as any)
       }
      })
      return remarkIds;
  }
  // 筛选id
  findFileId(files:any) {
    if(files == null) return;
    let filesId: string[] = []
    files.forEach(item => {
      if (item.checked) {
        filesId.push(item.fileId);
      }
    })
    return filesId;
  }

  // 获取任务列表
  getTasks(): void {
    this.taskService.getTasks(this.paramId).subscribe((tasks) => {
      let computedTasks = tasks.map(item => {
        if (item.taskData) {
          let taskData = JSON.parse(item.taskData);
          return {
            uploadTime: this.uploadTimeSplit(taskData.uploadTime),
            handleMatter: taskData.handleMatter,
            remarkList: this.remarkListProcess(taskData.result.remarkList, item.files?item.files:[]),
            files: this.filterList(item.files?item.files:[], taskData.result.lawDocs)
          }
        } else {
          return false;
        }
      })
      this.taskFiles = this.compact(computedTasks);

    })
  }

  // 任务列表数据构建remark(问题列表) filemeta(元数据查询列表)
  remarkListProcess(remarkList, fileMetaData) {
    let computedRemark = remarkList.map(item => {
      let attachmentList = item.current.attachmentList.concat(item.corrected.attachmentList);
      let descriptions = item.corrected.description
        ? [item.current.description].concat([item.corrected.description])
        : [item.current.description]
      return {
        attachmentList: this.filterList(fileMetaData, attachmentList),
        descriptions
      }
    })
    return computedRemark;
  }

  // 从数组中移除 falsey值。
  compact = (arr) => arr.filter(Boolean);

  // 任务更新时间处理
  uploadTimeSplit(time) {
    let date = new Date(time);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  }


  // 过滤数组   fileMetaFata  源文件数据    filterlist 终端需要过滤数据
  filterList(fileMetaData, filterList) {
    // 筛选出元数组在当前数组中id == metaId的数据
    let computedData = [];
    for (let i = 0; i < filterList.length; i++) {
      for (let j = 0; j < fileMetaData.length; j++) {
        if (filterList[i].id == fileMetaData[j].fileMetaId) {
          computedData.push(fileMetaData[j]);
        }
      }
    }
    return computedData;
  }

  // 复制问题列表
  copy(text) {
    ngCopy(text)
    this.message.create('success', `已复制`);
  }

  // 终端重命名
  rename(input) {
    input.value = this.renameFile.fileName.slice(0,this.renameFile.fileName.lastIndexOf('.'));
    input.setAttribute('type', 'text');
    this.moveToEnd(input);
    this.renameSpan = true;
    input.focus();
    
  }

  // 重命名input离开
  renameOnBlur(input){
    // input.value = ''
    // input.setAttribute('type', 'hidden');
    // this.renameSpan = false;
  }
  
  // 重命名确认
  renameOk(input){
    input.value = this.trim(input.value);
    let ext =  this.renameFile.fileName.slice(this.renameFile.fileName.lastIndexOf('.'));
    this.taskService.updateTaskFileName({ fileId: this.renameFile.fileId, fileNewName: input.value + ext }).subscribe(() => {
      this.message.create('success', `修改成功！`);
      this.renameSpan = false;
      this.renameFile.fileName = input.value + ext;
    }, (error) => {
      this.renameSpan = false;
      this.message.create('error', `修改失败！`);
    },()=>{
      input.value = ''
      input.setAttribute('type', 'hidden');
    })
  }

  moveToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
  } 
  // 终端预览
  preview(file) {
    if (file.ext == '.pdf') {
      file.checked = !file.checked;
    } else {
      this.showModal(file.mediaType, file.fileId, 'task')
    }
  }

  // 修改名称鼠标离开
  blurInput(item, input) {
    let copyName = item.fileName;
    input.value = this.trim(input.value);
    item.fileName = input.value;
    this.taskService.updateTaskFileName({ fileId: item.fileId, fileNewName: input.value + item.ext }).subscribe(() => {
      this.message.create('success', `修改成功！`);
    }, (error) => {
      this.message.create('error', `修改失败！`);
      item.fileName = copyName;
    })
    input.setAttribute('type', 'hidden');
    input.previousElementSibling.className = 'steps-file-fileName';
  }

  // 刷新文书 & 证据
  onRefinsh({ name }) {
    if (name === 'bizfile') {
      this.getFileList(this.paramId);
    } else {
      this.getEvidenceList(this.paramId);
    }
  }

  // 删除文书
  deleteBizfile(fileId: string, docSource: string, fileType: string,id:string): void {
      this.bizfileService.queryRelatedBizFileByDocid(id).subscribe((hasRelation)=>{
        let {data} = hasRelation;
        this.alert.confirm({
            title: '提示',
            msg: data?'此文书存在挂接关系，确认删除吗？':'确认删除吗？',
            icon:"warning",
            btnText:["确认",'取消'],
            result: (r) => {
                if (r){
                  if (docSource == '三方系统') {
                    this.taskService.deleteTaskFileStatus( id,  '0','response').subscribe((res:any)=>{
                      if(res.status == '200'){
                        this.getTasks();
                        this.getFileList(this.paramId);
                      }
                    })
                  } else {
                    this.caseDocService.bizfileDelete('0', fileId, this.paramId).subscribe((data: any) => {
                      this.onRefinsh({ name: 'bizfile' })
                    })
                  }
                }
            }
        });
      })
      return 
  }

  // 删除证据
  deleteEvidence(id: string, docSource: string): void {
      this.alert.confirm({
        title: '提示',
        msg: '确认删除吗？',
        icon:"warning",
        btnText:["确认",'取消'],
        result: (r) => {
            if (r){
              if (docSource == '三方系统') {
                this.taskService.deleteTaskFileStatus(id,  '1','response').subscribe((res:any)=>{
                  if(res.status == '200'){
                    this.getTasks();
                    this.getEvidenceList(this.paramId);
                  }
                })
              } else {
                this.evidence.evidenceIdDelete(id).subscribe((data: any) => {
                  this.onRefinsh({ name: 'evidence' })
                });
              }
            }
        }
    });
  }

  // 获取文件列表
  getFileList(paramId) {
    this.bizfileService.queryDocByPage(paramId, 0, 100).subscribe((res) => {
      if (res['code'] === 4) {
        const list = res['data']['data'];
        this.bizfile = list.filter((item) => item.doctype !== '其他');
        this.bizfileListOther = list.filter((item) => item.doctype === '其他');

        this.clearFileList();
        if (list.length > 0) {
          this.judgeLink(list, 'documentData');
        }
        // this.calcTerminalHeight();
      }
      this.cdRef.detectChanges();
      this.getUsersInfo(paramId);
    }, (error) => {
    });
  }

  // 获取证据列表
  getEvidenceList(paramId) {
    this.evidence.evidenceObjectIdObjectIdGet(paramId).subscribe((data: any) => {
      const evidenceList = data.data;
      this.evidenceList = data.data;
      this.clearEvidenceList();
      if (evidenceList.length > 0) {
        this.judgeLink(evidenceList, 'evidenceData');
      }

    });
  }

  // 每次更新刷新文书列表
  clearFileList() {
    this.processNodes.forEach(item => {
      item.documentData = []
    });
  }

  // 每次更新刷新证据列表
  clearEvidenceList() {
    this.processNodes.forEach(item => {
      item.evidenceData = []
    });
  }

  // 判断流程环节获取数据
  judgeLink(data, dataItemName) {
    if (!data) { return; }
    for (let i = 0; i < data.length; i++) {
      switch (data[i]['stage'] || data[i]['filingLink']) {
        case '线索核查':
        case '线索': {
          this.filterData('线索', dataItemName, data[i]);
        } break;
        case '立案': {
          this.filterData('立案', dataItemName, data[i]);
        } break;
        case '调查取证': {
          this.filterData('调查取证', dataItemName, data[i]);
        } break;
        case '处罚决定': {
          this.filterData('处罚决定', dataItemName, data[i]);
        } break;
        case '执行与结案': {
          this.filterData('执行与结案', dataItemName, data[i]);
        } break;
        case '强制执行': {
          this.filterData('强制执行', dataItemName, data[i]);
        } break;
      }
      if (dataItemName === 'documentData' && data[i]['doctype'] === '案件来源登记表') {
        this.registerContent = JSON.parse(data[i]['formJson'])['registerContent'];
        this.insertDate = data[i]['insertDate'];
      }
    }
  }

  //  颜色匹配
  badge(status: string): string {
    if (status === '已审批') {
      return 'badge-done';
    } else {
      return 'badge-success';
    }
  }

  // 筛选数据
  filterData(name, dataItemName, data) {
    if (!data || !name || !dataItemName) { return; }
    for (let j = 0; j < this.processNodes.length; j++) {
      if (this.processNodes[j]['name'] === name) {
        this.processNodes[j][dataItemName].push(data);
      }
    }
  }

  // 播放器ready
  onPlayerReady(api: VgAPI) {
    // console.log(api)
    this.api = api;
    this.api.isMasterDefined()
   
    this.api.getDefaultMedia().subscriptions.ended.subscribe(
      () => {
        // Set the video to the beginning
        // this.api.getDefaultMedia().currentTime = 0;
        console.log(this.api.getDefaultMedia())
      },
    );
  }
  
  public  typeFlag:boolean =false;
  // 文件详情弹框
  showModal(contentType, fileId, condition,attachment?): void {
    this.isVisible = true;
    this.fileId = fileId;
    this.publictypeFlag = contentType;

    // 证据查看
    if (condition === 'evidence') {
      this.renameIsShow = false;
        this.evidence.evidenceFileIdGet(fileId).subscribe((res:any)=>{
          this.afterLoadMedia(res);
      },(error)=>{
        this.message.create('error','证据下载失败！')
      })

    // 文书查看  
    } else if (condition === 'bizfile') {
      this.renameIsShow = false;
        this.bizfileService.downloadFile(fileId).subscribe((res:any) => {
          this.afterLoadMedia(res);
        }, (error) => { 
          this.message.create('error','文书查询失败！')
          this.handleCancel();
        });

    // 终端数据查看    
    } else if (condition === 'task') {
      if(!contentType.includes('pdf')){ 
        this.renameIsShow = true;
        this.renameFile = attachment;
      }
      this.taskService.downloadTaskFile(fileId).subscribe((res:any)=>{
        this.afterLoadMedia(res);
      }, (error) => { 
        this.message.create('error','文书查询失败！')
        this.handleCancel();
      })
    }
    
    if (contentType.includes('image') || contentType.includes('pdf')) {
  
    } else if (contentType.includes('audio')) {

    } else if (contentType.includes('video')) {

    }
  }

  // 视频音频加载后set操作
  afterLoadMedia(res){
    let url = URL.createObjectURL(res)
    this.url =  this.sanitizer.bypassSecurityTrustResourceUrl(url); 
    this.typeFlag = true;
  }

  // 加载pdf
  // afterLoadPdf($event) {
  //   this.loading = false;
  // }


  // 弹框确认
  handleOk(): void {
    this.isVisible = false;
  }
  // 弹框取消
  handleCancel(): void {
    this.renameSpan = false;
    this.isVisible = false;
    this.loading = false;
    this.typeFlag = false;
  }

  // 获取办案人 登记人信息
  getUsersInfo(paramId) {
    this.stakeHolderService.stakeHolderCaseIdCaseIdGet(paramId).subscribe((res) => {
      if (res['rel'] === true) {
        this.registUerName = res['data']['cmsCaseInfo']['registrant']['registerName'] || '';
        this.cmsCaseInfo = res['data']['cmsCaseInfo'];
        this.caseUserName = [];
        for (let i = 0; i < res['data']['caseHandlerInfo'].length; i++) {
          this.caseUserName.push(res['data']['caseHandlerInfo'][i]['userName']);
        }
      }
    }, (error) => {
    });
  }

  // 文字信息展开与收起
  toggle() {
    this.isOpen = !this.isOpen;
  }

  // 流程点击事件
  move(el) {
    const ele = this.el.nativeElement.querySelector(`.${el}`);
    if (ele) {
      ele.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'nearest' });
    }
  }



  // 文书编辑
  handleEdit(docid, doctype): void {
    if (doctype === '案件来源登记表') {
      this.router.navigate(['/main/home/handle/edithandle', this.paramId, docid, 'detail']);
      return;
    }
    this.caseReview.setShowWindow(true);
    this.caseReview.getCreateCaseDoc().emit({
      condition: 'New', docid, doctype, bizid: this.paramId, callback: () => {
        this.onRefinsh({ name: 'bizfile' })
      },
    });
  }

  
  // 查看文书
  view(docid, doctype, item) {
    if (item.docSource == '三方系统') {
      this.message.create('error', '不支持三方系统预览')
      return;
    }
    this.caseReview.setShowWindow(true);
    this.caseReview.getCreateCaseDoc().emit({ condition: 'See', docid, doctype, bizid: this.paramId, callback: () => { } });
  }


  // 下载文件
  download(fileid,fileName,downloadText) {
    if(downloadText === 'bizfile'){
      this.bizfileService.downloadFile(fileid).subscribe((res:any) => {
        this.createA2Click(res,fileName)
      }, (error) => { 
        this.message.create('error','文书下载失败！')
      });
    }else if(downloadText === 'evidence'){
      this.evidence.evidenceFileIdGet(fileid).subscribe((res:any)=>{
          this.createA2Click(res,fileName)
      },(error)=>{
        this.message.create('error','证据下载失败！')
      })
    }
  }

  createA2Click(res,fileName){
    const fileURL = URL.createObjectURL(res);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.download = fileName;
    a.href = fileURL;
    a.click();
  }



  // 获取文件流程
  getApproveFlow(id) {
    if (!id && id === undefined) { return; }
    if (this.docsService.get(id)) {
      this.approveFlow = this.docsService.get(id);
    } else {
      this.queryApproveFlow(id);
    }
  }

  // 通过文件ID查询文件流程
  queryApproveFlow(id) {
    this.bizfileService.queryApproveFlow(id).subscribe((data: any) => {
      if (data['code'] === 4 && data != 0) {
        this.approveFlow = data['data'];
        this.docsService.set(id, this.approveFlow);
      }
    }, (error) => {

    });
  }

  // 刷新文件流程
  approveReload(id) {
    this.queryApproveFlow(id);
  }


  //  trim 
  trim(str: string) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
  }

  // 查询元素
  findElement(parent: any, classname: string): any[] {
    const result: any = [];
    const next = (parentChild) => {
      for (let i = 0; i < parentChild.children.length; i++) {
        if (parentChild.children[i].className === classname) {
          result.push(parentChild.children[i]);
        } else {
          next(parentChild.children[i]);
        }
      }
    };
    next(parent);
    return result;
  }


  // 关闭卡片
  closeCard() {
    this.isExpand = false;
  }
  // 切换底部card
  cardToggle($event) {
    if ($event) {
      this.isExpand = $event
    }
  }


}
